package com.xbts.common.utils.aspose;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * WordsFileConvert
 *
 * @author swx
 * @version v1.0
 * @date 2022/10/27 17:14
 */
@Component
public class WordsFileConvert implements IFileConvert {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 验证license
     *
     * @return boolean
     */
    private boolean getLicense() {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try (InputStream is = loader.getResourceAsStream("license.xml")) {
            License license = new License();
            license.setLicense(is);
            return true;
        } catch (Exception e) {
           log.error("获取license失败", e);
        }
        return false;
    }

    @Override
    public InputStream fileToPdf(InputStream inputStream) {
        //去除水印
        if (!getLicense()) {
            return null;
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            Document doc = new Document(inputStream);
            doc.save(byteArrayOutputStream, SaveFormat.PDF);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (Exception e) {
            log.error("word转pdf失败", e);
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() {
        FileConvertConstant.WORDS_TO_PDF.forEach(word -> AsposeSingleton.instance().put(word, this));
    }

}
